
package session.stateless;

import entity.Holiday;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
public class HolidayBean implements HolidayBeanLocal {
    
    @PersistenceContext 
    private EntityManager em;
    
    public void createHoliday(String yearName, String monthName, String dayName, String event)
    {
        Holiday holiday = new Holiday();
        holiday.setYearName(Integer.parseInt(yearName));
        holiday.setMonthName(Integer.parseInt(monthName));
        holiday.setDayName(Integer.parseInt(dayName));
        holiday.setEvent(event);
        
        em.persist(holiday);
        em.flush();
    }
    
    public int getHolidayByMonth(String month)
    {
        int monthName = Integer.parseInt(month.substring(0, month.indexOf("/")));
        
        int yearName = Integer.parseInt(month.substring(month.indexOf("/") + 1));
        Query q = em.createQuery("SELECT h FROM Holiday h WHERE h.monthName=:monthName AND h.yearName=:yearName");
        q.setParameter("monthName", monthName);
        q.setParameter("yearName", yearName);
        
        List<Holiday> list = (List<Holiday>) q.getResultList();
        return list.size();
    }
    
    public int getHolidayByWeek(int startDay, int endDay, int month, int year)
    {
        Query q = em.createQuery("SELECT h FROM Holiday h WHERE h.monthName=:month AND h.yearName=:year");
        q.setParameter("month", month);
        q.setParameter("year", year);
        
        List<Holiday> list = (List<Holiday>) q.getResultList();
        
        int count = 0;
        for (Holiday h : list)
        {
            if ((h.getDayName() >= startDay) && (h.getDayName() <=endDay))
                count++;
        }
        
        return count;
    }
    
    public Boolean isHoliday(String day, String year)
    {
        int dayName = Integer.parseInt(day.substring(0, day.indexOf("/")));
        int monthName = Integer.parseInt(day.substring(day.indexOf("/") + 1));
        int yearName = Integer.parseInt(year);
        Holiday h = new Holiday();
        
        Query q = em.createQuery("SELECT h FROM Holiday h WHERE h.dayName =:dayName AND h.monthName=:monthName AND h.yearName=:yearName");
        q.setParameter("dayName", dayName);
        q.setParameter("monthName", monthName);
        q.setParameter("yearName", yearName);
        
        try {
            h = (Holiday) q.getSingleResult();
        }
        catch (NoResultException e)
        {
            return false;
        }
        
        return true;
    }
}
